﻿
//NOTE: this has been tested in IE only; cross browser support may require some extra cases to find selection text.
//          so, for now, only edit in IE.
function ApplyCodeBlock(langName) {

    if (langName == "defaultbutton") {
        return;
    }

    var selectedText = (document.all) ? document.selection.createRange() : document.getSelection(); 

    if (selectedText != null && selectedText.text != null && selectedText.text.length > 0) {
        wrapSelectionWithPreTags(langName, selectedText.text);
    }
}


/////// NOTE: This function was taken from http://jsfiddle.net/bXsWQ/, by Tim Down.
// This function sets the current selection to the selected text, wrapped inside of a pre-tag that
//       Syntax Highlighting javascript will read and re-format
function wrapSelectionWithPreTags(langName, selectedTextStr) {
    var sel, range, node;

    var html = "<pre class='brush: " + langName + "'>" + selectedTextStr + "</pre>";

    if (typeof window.getSelection != "undefined") {
        // IE 9 and other non-IE browsers
        sel = window.getSelection();

        // Test that the Selection object contains at least one Range
        if (sel.getRangeAt && sel.rangeCount) {
            // Get the first Range (only Firefox supports more than one)
            range = window.getSelection().getRangeAt(0);
            range.deleteContents();

            // Create a DocumentFragment to insert and populate it with HTML
            // Need to test for the existence of range.createContextualFragment
            // because it's non-standard and IE 9 does not support it
            if (range.createContextualFragment) {
                node = range.createContextualFragment(html);
            } else {
                // In IE 9 we need to use innerHTML of a temporary element
                var div = document.createElement("div"), child;
                div.innerHTML = html;
                node = document.createDocumentFragment();
                while ((child = div.firstChild)) {
                //while (child == div.firstChild) {
                    node.appendChild(child);
                }
            }
            range.insertNode(node);
        }
    } else if (document.selection && document.selection.type != "Control") {

        // IE 8 and below
        range = document.selection.createRange();
        range.pasteHTML(html);
    }
}